package com.lichuandi.reflect;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionExample {
    public static void main(String[] args) throws Exception {
        // 获取Class对象
        Class<?> clazz = Class.forName("com.lichuandi.reflect.User");

        // 创建实例
        Object user = clazz.getDeclaredConstructor().newInstance();

        // 获取并设置字段
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true); // 对于私有字段
        nameField.set(user, "John Doe");

        // 调用方法
        Method toStringMethod = clazz.getMethod("toString");
        String result = (String) toStringMethod.invoke(user);
        System.out.println(result);

        // 获取注解
        Annotation[] annotations = clazz.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation.annotationType().getName());
        }
    }
}